import { Controller, Get, Post, Body, Patch, Param, Delete, Req, Res, Inject, UseGuards, SetMetadata, Query, ParseIntPipe, Optional } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import * as svgCaptcha from 'svg-captcha';
import { GuardGuard } from '../../guard/guard.guard';
import { Role, ReqUrl } from '../../role/role.decorator'
import { AuthGuard } from '@nestjs/passport';
import { AdminGuard } from '@/common/gurads/admin.guard';
import { JwtGuard } from '@/common/gurads/jwt.guard';
import { Public } from '@/common/decorators/public.decorator';
import { Serialize } from '@/common/decorators/Serialize.decorator';
import { UserRepository } from './user.repository';
import { PublicUserDto } from '@/auth/dto/public-user.dto';
import { PublicUpdateUserDto } from './dto/public-update-user.dto';
import { Permission, Read } from '@/common/decorators/role-permission.decorator';
import { RolePermissionGuard } from '@/common/gurads/role-permission.guard';

@Controller('user')
@UseGuards(JwtGuard, AdminGuard, RolePermissionGuard)
@Permission('user')
export class UserController {
  constructor(
    @Inject('User') private readonly userService: UserService,
    @Inject('JD') private readonly jd: string[],
    @Inject('sync') private readonly test: string,
    @Inject('Config') private readonly baseUrl: any,
    @Optional() private userRepository: UserRepository,
  ) { }

  @Get('hello')
  // @SetMetadata('role', ['admin']) //第一个参数为key，第二个参数自定义我们的例子是数组存放的权限
  @Role(['admin'])  // 自定义装饰器
  getHello() {
    return 'Hello World!' + this.test + this.baseUrl.baseApi
  }

  @Get('code')
  createCaptcha(@Req() req, @Res() res) {
    const captcha = svgCaptcha.create({
      size: 4, // 验证码长度
      width: 100,
      height: 40,
      fontSize: 40,
      noise: 2,
      color: true,
      background: '#cc9966'
    });
    req.session.code = captcha.text;
    res.type('image/svg+xml');
    res.send(captcha.data);
  }

  @Post('login')
  createUser(@Req() req, @Body() body) {
    if (req.session?.code?.toLowerCase() === body?.code?.toLowerCase()) {
      return '登录成功'
    } else {
      return '验证码错误'
    }
  }

  @Post('/add/tags')
  addTags(@Body() params: { tags: string[], userId: number }) {
    return this.userService.addTags(params);
  }

  @Post()
  @Serialize(PublicUserDto)
  create(@Body() createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto);
  }

  @Get()
  @Read()
  findAllByRepository(
    @Query('page', new ParseIntPipe({ optional: true })) page,
    @Query('limit', new ParseIntPipe({ optional: true })) limit,
  ) {
    return this.userRepository.findAll(page, limit);
  }

  @Get()
  findAll(@Query() query: { keyWord: string, page: number, pageSize: number }) {
    return this.userService.findAll(query);
  }

  @Get(':username')
  @Serialize(PublicUserDto)
  findOneByRepository(@Param('username') username: string) {
    return this.userRepository.findOne(username);
  }

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: string) {    // 使用内置管道进行类型转换
    return this.userService.findOne(+id);
  }

  @Patch(':id')
  @Serialize(PublicUpdateUserDto)
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    // return this.userService.update(id, updateUserDto);
    return this.userRepository.update(updateUserDto);
  }

  @Delete(':id')
  delete(@Param('id') id: string) {
    return this.userRepository.delete(id);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.userService.remove(+id);
  }

  @Get()
  // @UseGuards(AuthGuard('jwt'))
  async findUser(@Query('id', ParseIntPipe) id: number, @Req() req) {
    return { id }
  }

  @Get('test')
  /**
   * 有个知识点：
   * 1。如果一个路由同时使用了多个守卫，会从上往下执行, 那么只有所有守卫都返回true时，才会执行该路由的处理函数。
   * 2。如果使用UseGuards传递多个守卫，会从前往后执行，如果前面的守卫返回false，则后面的守卫不会执行。
   */
  // @UseGuards(AuthGuard('jwt'))
  // @UseGuards(AdminGuard)
  // @Public()
  findTest() {
    return 'test'
  }
}
